<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_product\Entity\ShusyProduct;
use Drupal\shusy_product\Entity\ShusyProductStandard;
use Drupal\shusy_product_commission\Entity\ShusyProductCommission;
use Drupal\shusy_product_pintuan\Entity\ShusyProductPintuan;
use EntityListWrapper;
use Exception;

/**
 * @OA\Schema(
 *   schema="ProductItem",
 *   type="object",
 *   description="ProductItem"
 * )
 */
class ProductItem extends AbstractBaseModel {

  protected function getEntityType() {
    return 'shusy_product';
  }

  protected function setValue() {
    if ($this->entity instanceof ShusyProduct) {
      $value = [
        /**
         * @OA\Property(
         *   property="id",
         *   type="integer",
         *   description="ID",
         * ),
         */
        'id' => (int) $this->entity->id,
        'commisionTag' => $this->getCommisionTag($this->entity),
        /**
         * @OA\Property(
         *   property="name",
         *   type="string",
         *   description="产品名",
         * ),
         */
        'name' => (string) $this->entity->name,
        /**
         * @OA\Property(
         *   property="info",
         *   type="string",
         *   description="产品说明",
         * ),
         */
        'info' => (string) $this->entity->info,
        /**
         * @OA\Property(
         *   property="summary",
         *   type="string",
         *   description="摘要简介",
         * ),
         */
        'summary' => (string) $this->entity->summary,
        /**
         * @OA\Property(
         *   property="image",
         *   type="string",
         *   description="封面图",
         * ),
         */
        'image' => (string) $this->imageStyleUrl('ProductItemImage', $this->getImage()),
        /**
         * @OA\Property(
         *   property="price",
         *   type="number",
         *   description="价格 计算折扣后的价格",
         * ),
         */
        'price' => $this->convertYuan($this->getPrice()),
        /**
         * @OA\Property(
         *   property="cost",
         *   type="number",
         *   description="原价",
         * ),
         */
        'cost' => $this->convertYuan($this->getCost()),
        /**
         * @OA\Property(
         *   property="commission",
         *   type="number",
         *   description="佣金",
         * ),
         */
        'commission' => $this->convertYuan($this->getCost()),
        /**
         * @OA\Property(
         *   property="standards",
         *   type="array",
         *   description="规格",
         *   @OA\Items(ref="#/components/schemas/Standard")
         * ),
         */
        'standards' => $this->getStandards($this->entity),
        /**
         * @OA\Property(
         *   property="standards_pt",
         *   type="array",
         *   description="拼团规格 仅返回开启了拼团的规格",
         *   @OA\Items(ref="#/components/schemas/StandardPt")
         * ),
         */
        'standards_pt' => $this->getStandardsPt($this->entity),
        /**
         * @OA\Property(
         *   property="standards_ms",
         *   type="array",
         *   description="拼团规格 仅返回开启了秒杀的规格",
         *   @OA\Items(ref="#/components/schemas/StandardMs")
         * ),
         */
        'standards_ms' => $this->getStandardsMs($this->entity),
      ];
      $this->merge($value);

      //附加拼团信息
      $value = [
        /**
         * @OA\Property(
         *   property="number",
         *   type="integer",
         *   description="拼团成团人数",
         * ),
         */
        'number' => 0,
      ];
      $this->merge($value);
      $pintuan = $this->wrapper->pintuan->value();
      if ($pintuan instanceof ShusyProductPintuan) {
        if ($pintuan->status == 1) {
          $number = $pintuan->number;
          //覆盖价格信息
          $value = [
            /**
             * @OA\Property(
             *   property="pricePt",
             *   type="number",
             *   description="拼团最低价格",
             * ),
             */
            'pricePt' => $this->getStandardsMinPrice($this->value['standards_pt']),
            'number' => (int) $number,
          ];
          $this->merge($value);
        }
      }
      $end = strtotime($this->formatDate(REQUEST_TIME, 'Y-m-d')) + 24 * 60 * 60;
      //附加秒杀信息

      $stock = 0;
      $es = shusy_product_standard_load_multiple(FALSE, [
        'product_id' => $this->entity->id,
        'status' => 1,
      ]);
      foreach ($es as $e) {
        if ($e instanceof ShusyProductStandard) {
          try {
            $ew = $e->wrapper();
            $stock += $ew->stock->value();
          } catch (Exception $exception) {
            watchdog_exception(__FUNCTION__, $exception);
          }
        }
      }

      $value = [
        /**
         * @OA\Property(
         *   property="validity",
         *   type="integer",
         *   description="秒杀倒计时剩余秒",
         * ),
         */
        'validity' => (int) ($end - REQUEST_TIME),
        /**
         * @OA\Property(
         *   property="stock",
         *   type="integer",
         *   description="秒杀剩余库存",
         * ),
         */
        'stock' => (int) $stock,
        /**
         * @OA\Property(
         *   property="priceMs",
         *   type="number",
         *   description="秒杀最低价格",
         * ),
         */
        'priceMs' => $this->getStandardsMinPrice($this->value['standards_ms']),
      ];
      $this->merge($value);
    }
  }

  protected function getCommisionTag(ShusyProduct $shusyProduct) {
    $amount = 0;
    $es = shusy_product_commission_load_multiple(FALSE, ['product_id' => $shusyProduct->id]);
    if (!empty($es)) {
      $e = reset($es);
      if ($e instanceof ShusyProductCommission && $e->status == 1) {
        //返佣模式 1 固定金额 2 价格比例
        switch ($e->amount_type) {
          case 1:
            $amount = $e->amount_1;
            break;
          case 2:
            $standard = $this->wrapper->price->value();
            $amount = ($standard->amount * $e->amount_2) / 10000;
            break;
        }
      }
    }
    if ($amount > 0) {
      $pidProfit = variable_get_value('distribution_1_level_profit');
      $t = floor($pidProfit * $amount);
      if ($t > 0) {
        return "";
        return t("推荐奖励: @amount", ['@amount' => $this->convertYuan($t)]);
      }
    }
    return FALSE;
  }

  protected function getStandards(ShusyProduct $shusyProduct) {
    $list = [];
    $es = shusy_product_standard_load_multiple(FALSE, [
      'product_id' => $shusyProduct->id,
      'status' => 1,
    ]);
    foreach ($es as $e) {
      if ($e instanceof ShusyProductStandard) {
        try {
          $list[] = Standard::get($e->id);
        } catch (Exception $exception) {
          watchdog_exception(__FUNCTION__, $exception);
        }
      }
    }
    return $list;
  }

  protected function getStandardsPt(ShusyProduct $shusyProduct) {
    $list = [];
    $es = shusy_product_standard_load_multiple(FALSE, [
      'product_id' => $shusyProduct->id,
      'status' => 1,
    ]);
    foreach ($es as $e) {
      if ($e instanceof ShusyProductStandard) {
        try {
          $list[] = StandardPt::get($e->id);
        } catch (Exception $exception) {
          watchdog_exception(__FUNCTION__, $exception);
        }
      }
    }
    return $list;
  }

  protected function getStandardsMs(ShusyProduct $shusyProduct) {
    $list = [];
    $es = shusy_product_standard_load_multiple(FALSE, [
      'product_id' => $shusyProduct->id,
      'status' => 1,
    ]);
    foreach ($es as $e) {
      if ($e instanceof ShusyProductStandard) {
        try {
          $list[] = StandardMs::get($e->id);
        } catch (Exception $exception) {
          watchdog_exception(__FUNCTION__, $exception);
        }
      }
    }
    return $list;
  }

  protected function getStandardsMinPrice($list) {
    $prices = [];
    foreach ($list as $item) {
      $prices[] = $item['amount'];
    }
    if (!empty($prices)) {
      return min($prices);
    }
    return 0;
  }

  protected function getCost() {
    return $this->wrapper->price->cost->value();
  }

  protected function getImage() {
    $field_image = $this->wrapper->field_image->value();
    if (empty($field_image)) {
      $field_images = $this->wrapper->field_images;
      if ($field_images instanceof EntityListWrapper) {
        foreach ($field_images as $image) {
          $field_image = $image->value();
          break;
        }
      }
    }
    return $field_image;
  }

  protected function getPrice() {
    //最低价的规格
    $standard = $this->wrapper->price->value();
    //价格
    $amount = $standard->amount;
    $product = $this->entity;

    $context = [$product, $standard, $amount];

    //    drupal_alter('shushengyuan_product_amount_view', $amount, $context);

    return $amount;
  }

}
